<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/11/18
 * Time: 11:19
 */

namespace App\Http\Middleware;


use App\Utils\SecretChecker;
use App\Weixin\WechatClientFactory;
use App\Weixin\WeixinUtils;
use Closure;
use Illuminate\Support\Facades\Log;
use p5\objects\TimeUtils;

class WeixinAccessMiddleware
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (env("APP_ENV") != "prod") {
            return $next($request);
        }
        if (SecretChecker::isSafe($request)) {
            return $next($request);
        }

        // TODO 根据接入链接才能知道用哪个公司的 token 等进行校验
//        $client = WechatClientFactory::newClient($request->get("login_company_id"));
//        try {
//            if (!$client->valid()) {
//                Log::debug("微信验证不通过");
//                return "invalid access";
//            }
//        } catch (\Exception $e) {
//            return "invalid access";
//        }

        $echoStr = $request->get("echostr");
        if (!empty($echoStr)) {
            return $echoStr;
        }
        return $next($request);
    }

    public function logMsg()
    {
//        $type = $client->getRevType();
//        $data = $client->getRevData();
//        $string = json_encode($data);
//        $ctime = TimeUtils::format_time($client->getRevCtime() * 1);
//        $msg = new WeixinMsg();
//        $msg->set_from_user_name($client->getRevFrom());
//        $msg->set_to_user_name($client->getRevTo());
//        $msg->set_create_time($ctime);
//        $msg->set_content($string);
//        $msg->set_msg_type($client->getRevType());
//        $temp = $client->getRevEvent();
//        if (is_array($temp)) {
//            $keys = ["event", "key"];
//            foreach ($keys as $key) {
//                if (array_key_exists($key, $temp)) {
//                    $msg->set_event_name($temp[$key]);
//                    break;
//                }
//            }
//        }
        // $msg->save();
    }
}